<?php

define('DIR_BASE', implode(DS, array(APP::$ROOT, 'public', 'img', 'slideshow')));

class AdminHomeController extends AdminController {

    public function index() {
        $this->set('slideshow', SlideshowModel::build()->query());
    }

    public function create() {
        $this->render('form');
    }

    public function edit($id) {
        $this->set('slide', SlideshowModel::get($id));
        $this->render('form');
    }

    public function save() {
        $data = $this->POST('data');
        $data['image'] = preg_replace('/^\/?img\/slideshow\/?/i', '', $data['image']);
        $id       = (int)$data['id'];
        $newSlide = $id < 1;
                
        $oldData = $id>0 ? SlideshowModel::get($id) : false;
        $file = $this->getUploadImages('data_image_file', $data, $oldData);
        if ($file->error) {
            return $this->saveFailed($file->error, $data);
        }
        $data['image'] = $file->name();

        if (empty($data['image'])) {
            return $this->saveFailed('Morate odabrati sliku.', $data);
        }

        if ($newSlide) {
            unset($data['id']);
            $saved = SlideshowModel::insert($data);
            $id    = SlideshowModel::lastInsertId();
        } else {
            $saved = SlideshowModel::update($data, array('id' => $id));
        }

        if ($saved) {
            $file->process(DIR_BASE);

            $this->flash('Slajd je sačuvan', 'ok');
            $this->redirect('/admin_home/edit/' . $id);
        } else {
            $this->saveFailed('Greška pri čuvanju slajda.', $data);
        }
    }

    public function update_positions() {
        $positions = func_get_args();
        $saved = true;
        foreach ($positions as $pos) {
            list($id, $pos) = explode(';', $pos, 2);
            $saved = $saved && SlideshowModel::update(array('position' => $pos), array('id' => $id));
        }
        
        if ($saved) {
            $this->flash('Redosled je ažuriran', 'ok');
        } else {
            $this->flash('Greška. Redosled nije sačuvan.');
        }
        $this->redirect('/admin_home');
    }

    public function delete($id) {
        $slide = SlideshowModel::get($id);
        if (SlideshowModel::delete(array('id' => $id))) {
            @unlink(DIR_BASE . DS . $slide->image);
            $this->flash('Slajd je obrisan', 'ok');
        } else {
            $this->flash('Greška pri brisanju slajda.');
        }

        $this->redirect('/admin_home');
    }

    private function saveFailed($message, $data) {
        $this->flash($message);
        $this->set('slide', (object)$data);
        $this->render('form');
    }

}